var crypto = require('crypto');
var bcrypt = require('bcryptjs');

function getRandomString(len) {
  "use strict";
  if (!len) {
    len = 16;
  }
  var n = Math.ceil(len / 2);
  return crypto.randomBytes(n).toString('hex');

}

var should = require('should');
var mongoose = require('mongoose');
var User = require('../../app/models/user');
var User = mongoose.model('User');

//test User

describe('<Unit Test', function () {
  "use strict";
  // 建立测试账号
  describe('Model User:', function () {
    before(function (done) {
      user = {
        name: getRandomString(),
        password: 'password'
      };
      done();
    });

    // 测试之前不能已经存在测试账号
    describe("Before Method save", function () {
      it('should begin without test user', function (done) {
        User.find({
          name: user.name
        }, function (err, users) {
          User.find({
            name: user
          }, function (err, users) {
            users.should.have.length(0);
          });

          done();
        });
      });

    });

    // 测试保存用户
    describe("User save", function () {

      it('should begin without problems', function (done) {
        var _user = new User(user);

        _user.save(function (err) {
          should.not.exist(err);
          _user.remove(function (err) {
            should.not.exist(err);
            done();
          });
        });
      });

      it('should password be hashed correctly', function (done) {
        var password = user.password;
        var _user = new User(user);

        _user.save(function (err) {
          should.not.exist(err);
          _user.password.should.not.have.length(0);

          bcrypt.compare(password, _user.password, function (err, isMatch) {
            should.not.exist(err);
            isMatch.should.equal(true);

            _user.remove(function (err) {
              done();
            });
          });
        });
      });

      it('should have default role 0', function (done) {
        var password = user.password;
        var _user = new User(user);

        _user.save(function (err) {
          _user.role.should.equal(0);

          _user.remove(function (err) {
            done();
          });
        });
      });

      it('should fail to save an existing user', function (done) {
        var _user1 = new User(user);

        _user1.save(function (err) {
          should.not.exist(err);

          var _user2 = new User(user);

          _user2.save(function (err) {
            should.exist(err);

            _user1.remove(function (err) {
              if (!err) {
                _user2.remove(function (err) {
                  done();
                });
              }
            });
          });
        });
      });
    });

    // 测试后
    after(function (done) {
      //clear user info
      User.remove(user, function(err) {
        should.not.exist(err);
        done();
      });
    });
  });
});
